package com.cafuc.game;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class GamePanel extends JPanel {
    //创建坦克具体的
    Hero hero = new Hero();
    ArrayList<Missile> missiles= new ArrayList<>();
//
    Tanmap map= new Tanmap();
    public void paint(Graphics g) {
        //画背景
        g.drawImage(ImageUtil.readImg("imgs/chutian.jpg"), 0, 0, null);
        //画坦克,从hero取出
        g.drawImage(hero.image, hero.x, hero.y, null);


        //画炮弹
        for (int i=0;i<missiles.size();i++){
            //取出每个炮弹
            Missile m=missiles.get(i);
            g.drawImage(m.image,m.x,m.y,null);
        }
        for (int i = 0; i <map.walls.size() ; i++) {
            Walls w=map.walls.get(i);
            g.drawImage(w.image,w.x,w.y,null);
        }
    }


    public void watching() {
        //在方法中使用this表示当前对象，谁来调用谁就是当前对象

        //为当前画纸对象添加监听器
        MyKeyListener keyListener = new MyKeyListener();//创建监听器对象
        this.addKeyListener(keyListener);
        //语法规定
        this.setFocusable(true);
        this.requestFocus();
    }
    //用来处理自动控制的东西
    public void auto(){
        Timer timer = new Timer();//定时器
        TimerTask task = new TimerTask() {//定时器任务
            @Override
            //在run方法制定任务
            public void run() {
                //控制炮弹移动
                for(int i=0;i<missiles.size();i++){
                    Missile m = missiles.get(i);
                    m.move();
                    repaint();
                }
            }
        };
        //三个参数炮弹移动任务，延迟时间，间隔时间
        timer.schedule(task,0,30);
    }

    class MyKeyListener extends KeyAdapter {
        //用来监听键盘按压事件，只要按键盘就会自动调用
        public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if (keyCode == 38) {
                //让hero y属性变小
                hero.moveUp();

                System.out.println("你按了上方向键");
            } else if (keyCode == 40) {
                System.out.println("你按了下方向键");
                hero.moveDown();
            } else if (keyCode == 37) {
                hero.moveLeft();
                System.out.println("你按了左方向键");
            } else if (keyCode == 39) {
                hero.moveRight();
                System.out.println("你按了右方向键");
            }
            else if (keyCode ==32){
                Missile missile =hero.shoot();
                missiles.add(missile);
            }
//重画
            repaint();
        }
    }
}



